package com.link.base.base.report.controller;

import com.link.base.user.model.CoreUser;
import com.link.base.base.coupons.model.CollectRecord;
import com.link.base.base.order.model.SaleOrder;
import com.link.base.base.report.model.*;
import com.link.base.base.report.model.*;
import com.link.base.base.report.service.AccntReportService;
import com.link.base.base.saleactivity.model.RaffleDetail;
import com.link.base.base.saleactivity.model.SaleActivity;
import com.link.base.base.salestarget.model.SalesTarget;
import com.link.base.base.wechat.model.PageData;
import com.link.base.base.wechat.model.ProReport;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.ExportColumn;
import com.link.core.basic.query.QueryParams;
import com.link.core.modules.export.ExportFactory;
import com.link.core.modules.export.ExportWriter;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author unknown
 * @date unknown
 */
@Controller
@RequestMapping("/link/report")
public class AccntReportController {
    @Resource
    private AccntReportService accntReportService;

    /**
     * 各渠道任意时间段新增消费者报表
     * 查询出没一定时间段内每天的新增人数（分渠道的）
     * LJ
     */
    @RequestMapping(value = "/queryAccountEverydayCount", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryAccountEverydayCount(String startTime, String endTime, String type, String num) {
        Map<String, Object> map = new HashMap<>();
        //未定义
        String undefined = "undefined";
        try {
            if (null == startTime || undefined.equals(startTime)) {
                startTime = null;
            }
            if (null == endTime || undefined.equals(endTime)) {
                endTime = null;
            }
            if (num == null) {
                num = "0";
            }
            PortalBaseDataReport account = new PortalBaseDataReport();
            account.setAttr1(startTime);
            account.setAttr2(endTime);
            account.setAttr3(type);
            Integer number = Integer.parseInt(num);
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.DATE, -number);
            if (number > 0) {
                account.setAttr4(sdf.format(calendar.getTime()));
                account.setAttr5(sdf.format(date));
            }

            List<PortalBaseDataReport> accounts = accntReportService.queryAccountEverydayCount(account);
            List<String> result = new ArrayList<>();
            if (startTime != null) {
                result = accntReportService.getTimeList(startTime, endTime);
            } else {
                result = accntReportService.getTimeList(sdf.format(calendar.getTime()), sdf.format(date));
            }

            Map<String, Object> map2 = new HashMap<>();
            for (int i = 0; i < accounts.size(); i++) {
                String key = accounts.get(i).getCreated();
                map2.put(key, accounts.get(i).getAcctcount());
            }
            for (int i = 0; i < result.size(); i++) {
                if (null == map2.get(result.get(i))) {
                    PortalBaseDataReport addaccount = new PortalBaseDataReport();
                    addaccount.setAcctcount("0");
                    addaccount.setCreated(result.get(i));
                    accounts.add(addaccount);
                }
            }
            //排序
            Collections.sort(accounts, new Comparator() {
                @Override
                public int compare(Object o1, Object o2) {
                    PortalBaseDataReport stu1 = (PortalBaseDataReport) o1;
                    PortalBaseDataReport stu2 = (PortalBaseDataReport) o2;
                    return stu1.getCreated().compareTo(stu2.getCreated());
                }
            });
            if (startTime != null && endTime != null) {
                map.put("key", 1);
            } else if (number > 0) {
                map.put("key", 2);
            }
            map.put("rows", accounts);
            map.put("success", true);
        } catch (Exception e) {
            map.put("success", false);
            map.put("result", e.getMessage());
            LCLogger.withException(e);
        }
        return map;
    }

    /**
     * 门店或者经销商的月销售目标和实际销售目标的报表
     *
     * @return
     */
    @RequestMapping(value = "/querySalesTarget", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> querySalesTarget(SalesTarget salesTarget) {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> map2 = new HashMap<>();
        List<String> result = new ArrayList<>();
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
            // 获得一个日历的实例
            Calendar c = Calendar.getInstance();
            Date date = new Date();
            // 设置日历时间
            c.setTime(date);
            // 在日历的月份上退后6个月
            c.add(Calendar.MONTH, -5);
            String startTime = formatter.format(c.getTime()) + "-01 00:00:00";
            String endTime = formatter.format(date) + "-31 23:59:59";
            salesTarget.setStoreId(salesTarget.getStoreId());
            salesTarget.setStartTime(startTime);
            salesTarget.setEndTime(endTime);
            //attr1是门店首页报表标识
            String attr1 = "HOME";
            if (attr1.equals(salesTarget.getAttr1())) {
                CoreUser user = UserUtil.getUser();
                salesTarget.setOrgId(user.getOrgId());
                salesTarget.setAttr1(salesTarget.getAttr1());
            }
            result = accntReportService.getMonthBetween(startTime, endTime);
            List<SaleOrder> saleOrders = accntReportService.querySaleOrders(salesTarget);
            for (int i = 0; i < saleOrders.size(); i++) {
                String key = saleOrders.get(i).getAttr4();
                map2.put(key, saleOrders.get(i).getAttr5());
            }
            for (int i = 0; i < result.size(); i++) {
                if (null == map2.get(result.get(i))) {
                    SaleOrder saleOrder = new SaleOrder();
                    saleOrder.setAttr5("0");
                    saleOrder.setAttr4(result.get(i));
                    saleOrders.add(saleOrder);
                }
            }
            // 排序
            Collections.sort(saleOrders, new Comparator() {
                @Override
                public int compare(Object o1, Object o2) {
                    SaleOrder stu1 = (SaleOrder) o1;
                    SaleOrder stu2 = (SaleOrder) o2;
                    return stu1.getAttr4().compareTo(stu2.getAttr4());
                }
            });
            List<SalesTarget> salesTargets = accntReportService.querySalesTarget(salesTarget);
            map.put("salesTargets", salesTargets);
            map.put("saleOrders", saleOrders);
            map.put("success", true);
        } catch (Exception e) {
            map.put("success", false);
            map.put("result", e.getMessage());
            LCLogger.withException(e);
        }
        return map;
    }

    /**
     * 订单金额走势图
     *
     * @author 路江
     * @param storeReport
     * @return
     */
    @RequestMapping(value = "/orderTotalAmountForDay", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> orderTotalAmountForDay(@RequestBody StoreReport storeReport) {
        Map<String, Object> map = new HashMap<>(8);
        try {
            SaleOrder order = new SaleOrder();
            order.setAttr1(storeReport.getStartTime());
            order.setAttr2(storeReport.getEndTime());
            //销售订单
            order.setOrderType(storeReport.getOrderType());
            order.setAcctId(storeReport.getAcctId());
            order.setAttr3(storeReport.getQueryType());
            List<SaleOrder> list = accntReportService.queryorderTotalAmountForDay(order);
            List<String> result = new ArrayList<>();
            result = accntReportService.getTimeList(storeReport.getStartTime(), storeReport.getEndTime());
            Map<String, Object> map2 = new HashMap<>();
            for (int i = 0; i < list.size(); i++) {
                String key = list.get(i).getAttr4();
                map2.put(key, list.get(i).getAttr5());
            }
            for (int i = 0; i < result.size(); i++) {
                if (null == map2.get(result.get(i))) {
                    SaleOrder saleOrder = new SaleOrder();
                    saleOrder.setAttr5("0");
                    saleOrder.setAttr4(result.get(i));
                    list.add(saleOrder);
                }
            }
            // 排序
            Collections.sort(list, new Comparator() {
                @Override
                public int compare(Object o1, Object o2) {
                    SaleOrder stu1 = (SaleOrder) o1;
                    SaleOrder stu2 = (SaleOrder) o2;
                    return stu1.getAttr4().compareTo(stu2.getAttr4());
                }
            });
            map.put("list", list);
            map.put("success", true);
        } catch (Exception e) {
            map.put("success", false);
            map.put("result", e.getMessage());
            LCLogger.withException(e);
        }
        return map;
    }

    /**
     * 各产品的采购金额汇总。
     *
     * @author 路江
     * @param storeReport
     * @return
     */
    @RequestMapping(value = "/querySaleOrderPro", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> querySaleOrderPro(@RequestBody StoreReport storeReport) {
        Map<String, Object> map = new HashMap<>(8);
        try {
            SaleOrder order = new SaleOrder();
            order.setAttr1(storeReport.getStartTime());
            order.setAttr2(storeReport.getEndTime());
            order.setAcctId(storeReport.getAcctId());
            //销售订单
            order.setOrderType(storeReport.getOrderType());
            order.setAttr3(storeReport.getQueryType());
            List<SaleOrder> prolist = accntReportService.querySaleOrderPro(order);
            List<SaleOrder> brandlist = accntReportService.querySaleOrderProduct(order);
            List<ProReport> plist = new ArrayList<>();
            List<ProReport> blist = new ArrayList<>();
            List<String> blistName = new ArrayList<>();
            List<String> plistName = new ArrayList<>();
            for (int i = 0; i < prolist.size(); i++) {
                ProReport proReport = new ProReport();
                proReport.setName(prolist.get(i).getAttr3());
                if (null != prolist.get(i).getAttr4()) {
                    proReport.setValue(Double.parseDouble(prolist.get(i).getAttr4()));
                } else {
                    proReport.setValue(0);
                }

                plist.add(proReport);
                plistName.add(prolist.get(i).getAttr3());
            }
            for (int i = 0; i < brandlist.size(); i++) {
                ProReport proReport = new ProReport();
                proReport.setName(brandlist.get(i).getAttr5());
                if (null != brandlist.get(i).getAttr6()) {
                    proReport.setValue(Double.parseDouble(brandlist.get(i).getAttr6()));
                } else {
                    proReport.setValue(0);
                }
                blist.add(proReport);
                blistName.add(brandlist.get(i).getAttr5());
            }
            map.put("success", true);
            map.put("qprolist", plist);
            map.put("brandlist", blist);
            map.put("plistName", plistName);
            map.put("blistName", blistName);
        } catch (Exception e) {
            map.put("success", false);
            map.put("result", e.getMessage());
            LCLogger.withException(e);
        }

        return map;
    }

    @RequestMapping(value = "/querystoreSaleToday", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> querystoreSaleToday(String startTime, String endTime, String acctId, String orderType, String attr5) {

        Map<String, Object> map = new HashMap<>();
        try {
            SaleOrder order = new SaleOrder();
            order.setAttr1(startTime);
            order.setAttr2(endTime);
            order.setAcctId(Long.parseLong(acctId));
            //销售订单
            order.setOrderType(orderType);
            //attr5是门店销售业绩报表标识
            order.setAttr5(attr5);
            order.setOrgId(UserUtil.getUser().getOrgId());
            List<SaleOrder> prolist = accntReportService.querySaleOrderPro(order);
            List<ProReport> plist = new ArrayList<>();
            if (prolist != null && prolist.size() > 0) {
                for (int i = 0; i < prolist.size(); i++) {
                    ProReport proReport = new ProReport();
                    proReport.setName(prolist.get(i).getAttr3());
                    if (null != prolist.get(i).getAttr4()) {
                        proReport.setValue(Double.parseDouble(prolist.get(i).getAttr4()));
                    } else {
                        proReport.setValue(0);
                    }
                    plist.add(proReport);
                }
                map.put("qprolist", plist);
            } else {
                map.put("qprolist", prolist);
            }
            map.put("success", true);
        } catch (Exception e) {
            map.put("result", e.getMessage());
            map.put("success", false);
            LCLogger.withException(e);
        }
        return map;
    }

    /**
     * @Author wei xuan
     * @Description 根据时间区间查询产品的出入库数量汇总
     * @Created 11:55 2018/11/14
     * @Param [st
     **/
    @RequestMapping(value = "/queryProdStockChangeReport", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryProdStockChangeReport(@JsonParam SaleOrder order) {
        Map<String, Object> map = new HashMap<>();
        try {
            List<StockChangeReport> list = accntReportService.queryProdStockChangeReport(order);
            map.put("success", true);
            map.put("rows", list);
        } catch (Exception e) {
            map.put("success", false);
            map.put("result", e.getMessage());
            LCLogger.withException(e);
        }
        return map;
    }


    /**
     * 查询所选时间段内当前登陆用户对应的订单数量以及订单金额,
     * 查询所选时间段内当前登陆用户对应的退货单数量以及退货单金额
     *
     * @param startTime
     * @param endTime
     * @param acctId
     * @return
     */
    @RequestMapping(value = "/querySaleOrderSum", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> querySaleOrderSum(String startTime, String endTime, String acctId, String queryType) {
        Map<String, Object> map = new HashMap<>();
        try {
            SaleOrder order = new SaleOrder();
            order.setAttr1(startTime);
            order.setAttr2(endTime);
            // 1.采购数据汇总：procurementSum ；2.销售数据汇总：salesSum
            order.setAttr3(queryType);
            order.setAcctId(Long.parseLong(acctId));
            // 销售订单
            order.setOrderType("SalesOrder");
            //查询所选时间段内当前登陆用户对应的订单数量以及订单金额
            SaleOrder order2 = accntReportService.querySaleOrderSum(order);
            // 退货单
            order.setOrderType("SalesReturnOrder");
            //查询所选时间段内当前登陆用户对应的退货单数量以及退货单金额
            SaleOrder salesReturnOrder = accntReportService.querySaleOrderSum(order);

            map.put("order2", order2);
            map.put("SalesReturnOrder", salesReturnOrder);
            map.put("success", true);
        } catch (Exception e) {
            map.put("success", false);
            map.put("result", e.getMessage());
            LCLogger.withException(e);
        }

        return map;
    }

    /**
     * 数字化营销平台活动报表（优惠券和实物奖品）
     *
     * @param detail
     * @return
     */
    @RequestMapping(value = "/activetyReport", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> activetyReport(RaffleDetail detail) {
        Map<String, Object> map = new HashMap<>();
        try {
            List<RaffleDetail> raffle = accntReportService.activetyReport(detail);
            int countOfPeople = raffle.size();
            int count = 0;
            for (int i = 0; i < countOfPeople; i++) {
                if (null == raffle.get(i).getAttr1()) {
                    raffle.get(i).setAttr1("0");
                }
                count += Integer.parseInt(raffle.get(i).getAttr1());
            }
            map.put("countOfPeople", countOfPeople);
            map.put("count", count);
            //优惠券
            detail.setCouponsClass("Coupon");
            detail.setWinOrnot("Y");
            List<RaffleDetail> raffleDetail = accntReportService.activetyReport(detail);
            int numberOfPeople = raffleDetail.size();
            int number = 0;
            for (int i = 0; i < numberOfPeople; i++) {
                if (null == raffleDetail.get(i).getAttr1()) {
                    raffleDetail.get(i).setAttr1("0");
                }
                number += Integer.parseInt(raffleDetail.get(i).getAttr1());
            }
            map.put("numberOfPeople", numberOfPeople);
            map.put("number", number);
            //实物奖品
            detail.setCouponsClass("PhysicalGift");
            List<RaffleDetail> raffleDetail2 = accntReportService.activetyReport(detail);
            int numberOfPeople2 = raffleDetail2.size();
            int number1 = 0;
            for (int i = 0; i < numberOfPeople2; i++) {
                if (null == raffleDetail2.get(i).getAttr1()) {
                    raffleDetail2.get(i).setAttr1("0");
                }
                number1 += Integer.parseInt(raffleDetail2.get(i).getAttr1());
            }
            map.put("numberOfPeople2", numberOfPeople2);
            map.put("number1", number1);
            CollectRecord collectRecord = new CollectRecord();
            collectRecord.setAttr3(detail.getAttr3());
            collectRecord.setAttr4(detail.getAttr4());
            collectRecord.setAttr5(detail.getActivityId().toString());
            collectRecord.setAttr6("Coupon");
            List<CollectRecord> collectRecords = accntReportService.queryCollectRecord(collectRecord);
            int useNumberOfPeople = collectRecords.size();
            int useNumber = 0;
            for (int i = 0; i < useNumberOfPeople; i++) {
                if (null == collectRecords.get(i).getAttr1()) {
                    collectRecords.get(i).setAttr1("0");
                }
                useNumber += Integer.parseInt(collectRecords.get(i).getAttr1());
            }
            map.put("useNumberOfPeople", useNumberOfPeople);
            map.put("useNumber", useNumber);
            collectRecord.setAttr6("PhysicalGift");
            List<CollectRecord> collectRecords1 = accntReportService.queryCollectRecord(collectRecord);
            int physicalGiftNumberOfPeople = collectRecords.size();
            int physicalGiftNumber = 0;
            for (int i = 0; i < physicalGiftNumberOfPeople; i++) {
                if (null == collectRecords1.get(i).getAttr1()) {
                    collectRecords1.get(i).setAttr1("0");
                }
                physicalGiftNumber += Integer.parseInt(collectRecords1.get(i).getAttr1());
            }
            map.put("PhysicalGiftNumberOfPeople", physicalGiftNumberOfPeople);
            map.put("PhysicalGiftNumber", physicalGiftNumber);
            map.put("success", true);
        } catch (Exception e) {
            map.put("success", false);
            map.put("result", e.getMessage());
        }
        return map;
    }

    /**
     * 数字化营销平台活动报表（优惠券和实物奖品）
     *
     * @param saleActivity
     * @return
     */
    @RequestMapping(value = "/activetyReport1", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> activetyReport1(@RequestBody SaleActivity saleActivity) {
        Map<String, Object> map = new HashMap<>();
        List<String> result = new ArrayList<>();
        try {
            //获取两个日期之间的所有日期
            String startTime = saleActivity.getActivityStartDate();
            String endTime = saleActivity.getActivityEndDate();
            String[] number = saleActivity.getAccntStageArry();
            Long activityId = saleActivity.getId();
            result = accntReportService.getTimeList(startTime, endTime);
            map.put("size", result.size());
            for (int i = 0; i < number.length; i++) {
                if ("01".equals(number[i])) {
                    map.put("a", accntReportService.queryCouponForDay(startTime, endTime, number[i], activityId, result));
                }
                if ("02".equals(number[i])) {
                    map.put("b", accntReportService.querycollectRecordsForDay(startTime, endTime, number[i], activityId, result));
                }
                if ("03".equals(number[i])) {
                    map.put("c", accntReportService.queryCouponForDay(startTime, endTime, number[i], activityId, result));
                }
                if ("04".equals(number[i])) {
                    map.put("d", accntReportService.querycollectRecordsForDay(startTime, endTime, number[i], activityId, result));
                }
                if ("05".equals(number[i])) {
                    map.put("e", accntReportService.queryCouponForDaybynum(startTime, endTime, number[i], activityId, result));
                }
                if ("06".equals(number[i])) {
                    map.put("f", accntReportService.querycollectRecordsForDaynum(startTime, endTime, number[i], activityId, result));
                }
                if ("07".equals(number[i])) {
                    map.put("g", accntReportService.queryCouponForDaybynum(startTime, endTime, number[i], activityId, result));
                }
                if ("08".equals(number[i])) {
                    map.put("h", accntReportService.querycollectRecordsForDaynum(startTime, endTime, number[i], activityId, result));
                }
                if ("09".equals(number[i])) {
                    map.put("j", accntReportService.queryallCouponForDay(startTime, endTime, number[i], activityId, result));
                }
                if ("10".equals(number[i])) {
                    map.put("k", accntReportService.queryallCouponnum(startTime, endTime, number[i], activityId, result));
                }
            }

            map.put("success", true);
        } catch (Exception e) {
            map.put("success", false);
            map.put("result", e.getMessage());
        }
        return map;
    }

    @RequestMapping(value = "/exportActivetyReport", method = RequestMethod.POST)
    @ResponseBody
    @SuppressWarnings("unchecked")
    public Map<String, Object> exportActivetyReport(String startTime, String endTime, String[] number, Long activityId,
                                                    HttpServletRequest request, HttpServletResponse response, QueryParams qps) throws Exception {
        Map<String, Object> result = new HashMap<>();
        try {
            //获取数据
            List<PageData> list = new ArrayList<>();
            SaleActivity saleActivity = new SaleActivity();
            saleActivity.setActivityEndDate(endTime);
            saleActivity.setActivityStartDate(startTime);
            saleActivity.setId(activityId);
            saleActivity.setAccntStageArry(number);
            Map<String, Object> map = activetyReport1(saleActivity);
            List<RaffleDetail> details = (List<RaffleDetail>) map.get("a");
            List<CollectRecord> collectRecords = (List<CollectRecord>) map.get("b");
            List<RaffleDetail> details1 = (List<RaffleDetail>) map.get("c");
            List<CollectRecord> collectRecords1 = (List<CollectRecord>) map.get("d");
            List<RaffleDetail> details11 = (List<RaffleDetail>) map.get("e");
            List<CollectRecord> collectRecords11 = (List<CollectRecord>) map.get("f");
            List<RaffleDetail> details111 = (List<RaffleDetail>) map.get("g");
            List<CollectRecord> collectRecords111 = (List<CollectRecord>) map.get("h");

            int size = Integer.parseInt(map.get("size").toString());
            for (int i = 0; i < size; i++) {
                PageData data = new PageData();
                list.add(data);
            }
            for (int i = 0; i < size; i++) {
                if (null != details) {
                    list.get(i).setAttr1(details.get(i).getAttr5());
                    list.get(i).setDate(details.get(i).getAttr4());
                }
                if (null != collectRecords) {
                    list.get(i).setAttr2(collectRecords.get(i).getAttr5());
                    list.get(i).setDate(collectRecords.get(i).getAttr4());
                }
                if (null != details1) {
                    list.get(i).setAttr3(details1.get(i).getAttr5());
                    list.get(i).setDate(details1.get(i).getAttr4());
                }
                if (null != collectRecords1) {
                    list.get(i).setAttr4(collectRecords1.get(i).getAttr5());
                    list.get(i).setDate(collectRecords1.get(i).getAttr4());
                }
                if (null != details11) {
                    list.get(i).setAttr5(details11.get(i).getAttr5());
                    list.get(i).setDate(details11.get(i).getAttr4());
                }
                if (null != collectRecords11) {
                    list.get(i).setAttr6(collectRecords11.get(i).getAttr5());
                    list.get(i).setDate(collectRecords11.get(i).getAttr4());
                }
                if (null != details111) {
                    list.get(i).setAttr7(details111.get(i).getAttr5());
                    list.get(i).setDate(details111.get(i).getAttr4());
                }
                if (null != collectRecords111) {
                    list.get(i).setAttr8(collectRecords111.get(i).getAttr5());
                    list.get(i).setDate(collectRecords111.get(i).getAttr4());
                }
            }
            qps.setTotal(size);
            ExportColumn column = new ExportColumn();
            ExportColumn column1 = new ExportColumn();
            ExportColumn column8 = new ExportColumn();
            column8.setField("date");
            column.setField("attr1");
            column1.setField("attr2");
            ExportColumn column2 = new ExportColumn();
            column2.setField("attr3");
            ExportColumn column3 = new ExportColumn();
            column3.setField("attr4");
            ExportColumn column4 = new ExportColumn();
            column4.setField("attr5");
            ExportColumn column5 = new ExportColumn();
            column5.setField("attr6");
            ExportColumn column6 = new ExportColumn();
            column6.setField("attr7");
            ExportColumn column7 = new ExportColumn();
            column7.setField("attr8");
            column.setTitle("优惠券中奖人数");
            column1.setTitle("优惠券使用人数");
            column2.setTitle("实物奖品中奖人数");
            column3.setTitle("实物奖品兑换人数");
            column4.setTitle("优惠券中奖次数");
            column5.setTitle("优惠券使用次数");
            column6.setTitle("实物奖品中奖次数");
            column7.setTitle("实物奖品兑换次数");
            column8.setTitle("活动时间");
            column.setOrder(1);
            column1.setOrder(2);
            column2.setOrder(3);
            column3.setOrder(4);
            column4.setOrder(5);
            column5.setOrder(6);
            column6.setOrder(7);
            column7.setOrder(8);
            column8.setOrder(0);
            List<ExportColumn> exportColumns = new ArrayList<>();
            exportColumns.add(column7);
            exportColumns.add(column6);
            exportColumns.add(column5);
            exportColumns.add(column4);
            exportColumns.add(column3);
            exportColumns.add(column2);
            exportColumns.add(column1);
            exportColumns.add(column);
            exportColumns.add(column8);
            qps.setExportColumns(exportColumns);
            ExportWriter exportWriter = ExportFactory.newExcelInstance(qps);
            exportWriter.wirteData(list);
            result.put("url", exportWriter.getUrlPath());
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
        }

        return result;
    }

    /**
     * 活动效果整体统计
     *
     * @param saleActivity
     * @return
     */
    @RequestMapping(value = "/campaignResult", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> campaignResult(@RequestBody SaleActivity saleActivity) {
        Map<String, Object> map = new HashMap<>();
        try {
            SaleActivity activity = new SaleActivity();
            activity = accntReportService.activitycount(activity);
            CollectRecord collectRecord = new CollectRecord();
            collectRecord.setAttr1(saleActivity.getActivityStartDate());
            collectRecord.setAttr2(saleActivity.getActivityEndDate());
            collectRecord.setAttr3(saleActivity.getAttr3());
            //领取优惠券人数和次数
            List<CollectRecord> collectRecords = accntReportService.queryCouponscount(collectRecord);
            Integer sum = 0;
            Integer sum1 = 0;
            for (int i = 0; i < collectRecords.size(); i++) {
                sum += Integer.parseInt(collectRecords.get(i).getAttr3());
            }
            //使用优惠券人数和次数
            List<CollectRecord> collectRecordsUse = accntReportService.queryCouponsUsecount(collectRecord);
            for (int i = 0; i < collectRecordsUse.size(); i++) {
                sum1 += Integer.parseInt(collectRecordsUse.get(i).getAttr3());
            }

            map.put("count", activity.getAttr1());
            map.put("claimOfPeople", collectRecords.size());
            map.put("claimOfCount", sum);
            map.put("useOfPeople", collectRecordsUse.size());
            map.put("useOfCount", sum1);
            map.put("success", true);
        } catch (Exception e) {
            map.put("success", false);
            map.put("result", e.getMessage());
        }

        return map;

    }

    @RequestMapping(value = "/campaignResultReport", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> campaignResultReport(@RequestBody SaleActivity saleActivity) {
        Map<String, Object> map = new HashMap<>();
        List<String> result = new ArrayList<>();
        try {
            String startT = saleActivity.getActivityStartDate();
            String endT = saleActivity.getActivityEndDate();
            String[] number = saleActivity.getAccntStageArry();
            Long id = saleActivity.getId();
            result = accntReportService.getTimeList(startT, endT);
            map.put("size", result.size());
            for (int i = 0; i < number.length; i++) {
                if ("NumberOfActivities".equals(number[i])) {
                    //活动数量
                    map.put("a", accntReportService.NumberOfActivities(startT, endT, number[i], result));
                }
                if ("CouponsNumberOfPeople".equals(number[i])) {
                    //优惠券领取人数
                    String type = "claim";
                    map.put("b", accntReportService.CouponsNumberOfPeople(startT, endT, number[i], result, type, id.toString()));
                }
                if ("CouponsNumber".equals(number[i])) {
                    //优惠券领取次数
                    String type = "claim";
                    map.put("c", accntReportService.CouponsNumber(startT, endT, number[i], result, type, id.toString()));
                }
                if ("CouponsUseOfPeople".equals(number[i])) {
                    //优惠券使用人数
                    String type = "use";
                    map.put("d", accntReportService.CouponsNumberOfPeople(startT, endT, number[i], result, type, id.toString()));
                }
                if ("CouponsUseNumber".equals(number[i])) {
                    //优惠券使用次数
                    String type = "use";
                    map.put("e", accntReportService.CouponsNumber(startT, endT, number[i], result, type, id.toString()));
                }

            }
            map.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            map.put("success", false);
            map.put("result", e.getMessage());
        }
        return map;
    }

    /**
     * 导出活动结果统计
     */
    @RequestMapping(value = "/campaignResultExport", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> campaignResultExport(String startTime, String endTime, String[] number, String id, String type,
                                                    HttpServletRequest request, HttpServletResponse response, QueryParams qps) throws Exception {
        SaleActivity saleActivity = new SaleActivity();
        saleActivity.setActivityEndDate(endTime);
        saleActivity.setActivityStartDate(startTime);
        saleActivity.setId(Long.parseLong(id));
        saleActivity.setAccntStageArry(number);
        Map<String, Object> map = campaignResultReport(saleActivity);
        return accntReportService.campaignResultExport(map, qps, type);
    }

    /**
     * 导出活动结果统计
     */
    @RequestMapping(value = "/campaignActivityResultExport", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> campaignActivityResultExport(String startTime, String endTime, String[] number, String id, HttpServletRequest request,
                                                            HttpServletResponse response, QueryParams qps) throws Exception {
        SaleActivity saleActivity = new SaleActivity();
        saleActivity.setActivityEndDate(endTime);
        saleActivity.setActivityStartDate(startTime);
        saleActivity.setId(Long.parseLong(id));
        saleActivity.setAccntStageArry(number);
        Map<String, Object> map = campaignResultReport(saleActivity);
        return accntReportService.campaignActivityResultExport(map, qps);
    }

    @RequestMapping(value = "/querySalesTargetByShopper", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> querySalesTargetByShopper(SalesTarget salesTarget) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获得一个日历的实例
            Calendar start = Calendar.getInstance();
            // 获得一个日历的实例
            Calendar end = Calendar.getInstance();
            Date date = new Date();
            // 设置日历时间
            start.setTime(date);
            // 设置日历时间
            end.setTime(date);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            // 在日历的月份上退后6个月
            start.add(Calendar.DAY_OF_MONTH, -6);
            // 在日历的月份上退后6个月
            end.add(Calendar.DAY_OF_MONTH, 1);
            salesTarget.setStartTime(formatter.format(start.getTime()) + " 23:59:59");
            salesTarget.setEndTime(formatter.format(end.getTime()) + " 00:00:00");
            CoreUser user = UserUtil.getUser();
            salesTarget.setOrgId(user.getOrgId());
            List<SalesTarget> salesTargetList = accntReportService.querySalesTargetByShopper(salesTarget);
            List<SaleOrder> saleOrderList = accntReportService.querySaleOrdersByShopper(salesTarget);
            result.put("success", true);
            result.put("salesTargets", salesTargetList);
            result.put("saleOrders", saleOrderList);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
            LCLogger.withException(e);
        }
        return result;
    }

    /**
     * 查询目标达成报表数据
     *
     * @author NingLanhao
     * @date 2018-12-26 20:16
     * @param goalAchievement
     * @return java.util.Map
     */
    @RequestMapping(value = "/queryGoalAchievement", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryGoalAchievement(GoalAchievement goalAchievement) {
        Map<String, Object> result = new HashMap<>(2);
        try {
            GoalAchievement data = accntReportService.queryGoalAchievement(goalAchievement);
            result.put("success", true);
            result.put("result", data);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
            LCLogger.withException(e);
        }
        return result;
    }

    @RequestMapping(value = "/queryAcctAnysReport", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryAcctAnysReport(AcctAnys acctAnys) {
        Map<String, Object> result = new HashMap<>(2);
        try {
            AcctAnys data = accntReportService.queryAcctAnysReport(acctAnys);

            result.put("success", true);
            result.put("result", data);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
            LCLogger.withException(e);
        }
        return result;
    }

    @RequestMapping(value = "/queryByAcctAnysNoMonthDetail", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryByAcctAnysNoMonthDetail(AcctAnys acctAnys) {
        Map<String, Object> result = new HashMap<>(2);
        try {
            List<AcctAnys> datalist = accntReportService.queryByAcctAnysNoMonthDetail(acctAnys);

            result.put("success", true);
            result.put("rows", datalist);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
            LCLogger.withException(e);
        }
        return result;
    }

    @RequestMapping(value = "/queryByAcctAnysNoMonthDetail/exportData", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryDataByAcctAnysNoMonthDetail(AcctAnys acctAnys,HttpServletRequest request,QueryParams qps) {
        Map<String, Object> result = new HashMap<>(2);
        try {
            qps.preDealSecurity(request);
            ExportWriter exportWriter;
            String exportType = "xlsx";
            String exportFileType = qps.getExportFileType();
            if (exportType.equals(exportFileType)) {
                exportWriter = ExportFactory.newExcelInstance(qps);
            } else {
                exportWriter = ExportFactory.newInstance(qps);
            }
            // 此处仅用于传递参数
            AcctAnys entity = (AcctAnys) BasicModel.transformClass(acctAnys.getClass(), qps);
            List<AcctAnys> datalist = accntReportService.queryByAcctAnysNoMonthDetail(acctAnys);
            for (AcctAnys record : datalist ) {
                String acctType = "Dealer";
                if (!acctType.equals(record.getAcctType())) {
                    record.setAcctType("门店");
                } else {
                    record.setAcctType("经销商");
                }
            }
            exportWriter.wirteData(datalist);
            result.put("success", true);
            result.put("url", exportWriter.getUrlPath());
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
            LCLogger.withException(e);
        }
        return result;
    }

    @RequestMapping(value = "/queryMonthTargetSale", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryMonthTargetSale(AcctAnys acctAnys) {
        Map<String, Object> result = new HashMap<>(2);
        try {
            AcctAnys entity = accntReportService.queryMonthTargetSale(acctAnys);
            result.put("success", true);
            result.put("result", entity);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
            LCLogger.withException(e);
        }
        return result;
    }

    @RequestMapping(value = "/queryMonthTargetSaleDetail", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryMonthTargetSaleDetail(AcctAnys acctAnys) {
        Map<String, Object> result = new HashMap<>(2);
        try {
            List<AcctAnys> dataList = accntReportService.queryMonthTargetSaleDetail(acctAnys);
            result.put("success", true);
            result.put("rows", dataList);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
            LCLogger.withException(e);
        }
        return result;
    }

    /**
     * 根据输入的时间查询消费者推荐排行报表
     * @author daichenyu
     * @date 2019/03/05
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return
     */
    @RequestMapping(value = "/queryAcctCampByDateRange", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryAcctCampByDateRange(String startTime, String endTime) {
        Map<String, Object> result = new HashMap<>(2);
        try {
            List<AcctCampReport> dataList = accntReportService.queryAcctCampByDateRange(startTime,endTime);
            result.put("success", true);
            result.put("rows", dataList);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
            LCLogger.withException(e);
        }
        return result;
    }

    /**
     * 本周、本月、本年的查询消费者推荐排行报表
     * @author daichenyu
     * @date 2019/03/05
     * @param latelyNum 判断本周本月还是本年的标志
     * @return
     */
    @RequestMapping(value = "/queryAcctCamp", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryAcctCamp(String latelyNum) {
        Map<String, Object> result = new HashMap<>(2);
        try {
            List<AcctCampReport> dataList = accntReportService.queryAcctCamp(latelyNum);
            result.put("success", true);
            result.put("rows", dataList);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
            LCLogger.withException(e);
        }
        return result;
    }

    @RequestMapping(value = "/queryMonthTargetSaleDetail/exportData", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryDataByMonthTargetSaleDetail(AcctAnys acctAnys,HttpServletRequest request,QueryParams qps) {
        Map<String, Object> result = new HashMap<>(2);
        try {
            qps.preDealSecurity(request);
            ExportWriter exportWriter;
            String exportType = "xlsx";
            String exportFileType = qps.getExportFileType();
            if (exportType.equals(exportFileType)) {
                exportWriter = ExportFactory.newExcelInstance(qps);
            } else {
                exportWriter = ExportFactory.newInstance(qps);
            }
            // 此处仅用于传递参数
            AcctAnys entity = (AcctAnys) BasicModel.transformClass(acctAnys.getClass(), qps);
            List<AcctAnys> datalist = accntReportService.queryMonthTargetSaleDetail(acctAnys);
            for (AcctAnys record : datalist ) {
                String acctType = "Dealer";
                if (acctType.equals(record.getAcctType())) {
                    record.setAcctType("经销商");
                } else {
                    record.setAcctType("门店");
                }
            }
            exportWriter.wirteData(datalist);
            result.put("success", true);
            result.put("url", exportWriter.getUrlPath());
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
            LCLogger.withException(e);
        }
        return result;
    }
}
